<?php

namespace app\admin\controller\manufacture;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 库存管理
 *
 * @icon fa fa-warehouse
 * @remark 管理物料库存信息
 */
class Stock extends Backend
{
    /**
     * Stock模型对象
     * @var \app\admin\model\manufacture\Stock
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\manufacture\Stock;
        $this->view->assign("typeList", $this->model->getTypeList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['material.category', 'warehouse'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        // 获取物料列表
        $materialList = \app\admin\model\manufacture\Material::with('category')
            ->where('status', 1)
            ->select();
        $this->view->assign('materialList', $materialList);
        
        // 获取仓库列表
        $warehouseList = \app\admin\model\manufacture\Warehouse::where('status', 1)->select();
        $this->view->assign('warehouseList', $warehouseList);
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                
                // 检查是否已存在该物料在该仓库的库存记录
                $existingStock = $this->model->where('material_id', $params['material_id'])
                    ->where('warehouse_id', $params['warehouse_id'])
                    ->find();
                
                if ($existingStock) {
                    $this->error('该物料在此仓库已有库存记录，请使用入库/出库功能');
                }
                
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取物料列表
        $materialList = \app\admin\model\manufacture\Material::with('category')
            ->where('status', 1)
            ->select();
        $this->view->assign('materialList', $materialList);
        
        // 获取仓库列表
        $warehouseList = \app\admin\model\manufacture\Warehouse::where('status', 1)->select();
        $this->view->assign('warehouseList', $warehouseList);
        
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $item) {
                    $count += $item->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        } else {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
    }

    /**
     * 入库
     */
    public function inbound($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $quantity = $this->request->post('quantity');
            $remark = $this->request->post('remark');
            
            if (!is_numeric($quantity) || $quantity <= 0) {
                $this->error('入库数量必须大于0');
            }
            
            Db::startTrans();
            try {
                // 更新库存数量
                $row->quantity += $quantity;
                $row->save();
                
                // 记录入库日志
                \app\admin\model\manufacture\StockLog::create([
                    'stock_id' => $row->id,
                    'type' => 'in',
                    'quantity' => $quantity,
                    'before_quantity' => $row->quantity - $quantity,
                    'after_quantity' => $row->quantity,
                    'operator_id' => $this->auth->id,
                    'remark' => $remark,
                    'createtime' => time()
                ]);
                
                Db::commit();
                $this->success('入库成功');
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 出库
     */
    public function outbound($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $quantity = $this->request->post('quantity');
            $remark = $this->request->post('remark');
            
            if (!is_numeric($quantity) || $quantity <= 0) {
                $this->error('出库数量必须大于0');
            }
            
            if ($quantity > $row->quantity) {
                $this->error('出库数量不能大于当前库存');
            }
            
            Db::startTrans();
            try {
                // 更新库存数量
                $row->quantity -= $quantity;
                $row->save();
                
                // 记录出库日志
                \app\admin\model\manufacture\StockLog::create([
                    'stock_id' => $row->id,
                    'type' => 'out',
                    'quantity' => $quantity,
                    'before_quantity' => $row->quantity + $quantity,
                    'after_quantity' => $row->quantity,
                    'operator_id' => $this->auth->id,
                    'remark' => $remark,
                    'createtime' => time()
                ]);
                
                Db::commit();
                $this->success('出库成功');
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 库存盘点
     */
    public function check()
    {
        if ($this->request->isPost()) {
            $stockId = $this->request->post('stock_id');
            $actualQuantity = $this->request->post('actual_quantity');
            $remark = $this->request->post('remark');
            
            $stock = $this->model->get($stockId);
            if (!$stock) {
                $this->error('库存记录不存在');
            }
            
            if (!is_numeric($actualQuantity) || $actualQuantity < 0) {
                $this->error('实际数量不能为负数');
            }
            
            Db::startTrans();
            try {
                $beforeQuantity = $stock->quantity;
                $stock->quantity = $actualQuantity;
                $stock->save();
                
                // 记录盘点日志
                \app\admin\model\manufacture\StockLog::create([
                    'stock_id' => $stock->id,
                    'type' => 'check',
                    'quantity' => $actualQuantity - $beforeQuantity,
                    'before_quantity' => $beforeQuantity,
                    'after_quantity' => $actualQuantity,
                    'operator_id' => $this->auth->id,
                    'remark' => $remark,
                    'createtime' => time()
                ]);
                
                Db::commit();
                $this->success('盘点完成');
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        
        // 获取库存列表
        $stockList = $this->model->with(['material.category', 'warehouse'])
            ->where('quantity', '>', 0)
            ->select();
        $this->view->assign('stockList', $stockList);
        
        return $this->view->fetch();
    }

    /**
     * 库存预警
     */
    public function warning()
    {
        $list = $this->model->with(['material.category', 'warehouse'])
            ->where('quantity', '<=', Db::raw('material.min_stock'))
            ->where('material.min_stock', '>', 0)
            ->select();
        
        $this->view->assign('list', $list);
        return $this->view->fetch();
    }
}
